package com.bungarus.helper;

import com.bungarus.busi.SessionManagement;
import io.lettuce.core.*;
import org.springframework.core.env.Environment;

import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * Created by tang on 2019/3/12.
 */
public class RedisCacheHelper {
    private static final String GROUP_SERVICE_REDIS_HOST = "bungarus.gs.redis.host";
    private static final String GROUP_SERVICE_REDIS_PORT = "bungarus.gs.redis.port";
    private static final String GROUP_SERVICE_REDIS_DB = "bungarus.gs.redis.db";
    private static final String GROUP_SERVICE_REDIS_OPS_TIMEOUT = "bungarus.gs.redis.timeout";

    public static long REDIS_CACHE_TIMEOUT = 0;

    public static RedisClient initRedisClient() {
        Environment environment = SessionManagement.springCtx.getEnvironment();
        RedisURI uri = RedisURI.create(environment.getProperty(GROUP_SERVICE_REDIS_HOST, String.class),
                environment.getProperty(GROUP_SERVICE_REDIS_PORT, Integer.class, 6379));
        uri.setDatabase(environment.getProperty(GROUP_SERVICE_REDIS_DB, Integer.class, 0));

        REDIS_CACHE_TIMEOUT = environment.getProperty(GROUP_SERVICE_REDIS_OPS_TIMEOUT, Integer.class, 10000);
        uri.setTimeout(Duration.of(REDIS_CACHE_TIMEOUT, ChronoUnit.MILLIS));

        RedisClient client = RedisClient.create(uri);
        client.setOptions(ClientOptions.builder()
                .autoReconnect(true)
                .pingBeforeActivateConnection(true)
                .socketOptions(SocketOptions.builder().tcpNoDelay(true).build())
                .build());

        return client;
    }

    public static void shutdownRedisClient(RedisClient client) {
        if(null != client) {
            client.shutdown();
        }
    }

    public static <V> V getFutureValue(RedisFuture<V> future) {
        try {
            return future.get(REDIS_CACHE_TIMEOUT, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
        return null;
    }

}
